﻿using Serilog;
using Serilog.Events;
using Serilog.Filters;
using Serilog.Formatting.Compact;
using Serilog.Formatting.Json;
using Serilog.Sinks.SystemConsole.Themes;

namespace In66.Web
{
    public static class SevicesExtension
    {

        /// <summary>
        /// 日志推送
        /// </summary>
        /// <param name="services"></param>
        /// <param name="Configuration"></param>
        /// <returns></returns>
        public static IServiceCollection AddSeriLog(this IServiceCollection services, IConfiguration Configuration)
        {
            services.AddSingleton(sp =>
            {
                //创建文件夹Linux的正斜杆
                string LogFilePath(string LogEvent) => $@"{AppDomain.CurrentDomain.BaseDirectory}//logs//{LogEvent}//.log";

                var logger = new LoggerConfiguration()
                             .MinimumLevel.Warning()
                             .ReadFrom.Configuration(Configuration)
                             .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                             .MinimumLevel.Override("System", LogEventLevel.Warning)
                             //.WriteTo.Console(LogEventLevel.Warning, theme: AnsiConsoleTheme.Code)
                             //.WriteTo.Console(new RenderedCompactJsonFormatter())
                             .Enrich.FromLogContext()
                             .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Warning).WriteTo.File(new CompactJsonFormatter(), LogFilePath("warning"), rollingInterval: RollingInterval.Day))
                             .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Error).WriteTo.File(new CompactJsonFormatter(), LogFilePath("error"), rollingInterval: RollingInterval.Day))
                             .WriteTo.Logger(lg => lg.Filter.ByIncludingOnly(p => p.Level == LogEventLevel.Fatal).WriteTo.File(new CompactJsonFormatter(), LogFilePath("fatal"), rollingInterval: RollingInterval.Day));

                Log.Logger = logger.CreateLogger();

                return Log.Logger;
            });

            services.AddSingleton((Func<IServiceProvider, ILoggerFactory>)((IServiceProvider provider) => new Serilog.Extensions.Logging.SerilogLoggerFactory(provider.GetService<Serilog.ILogger>())));

            return services;
        }
    }
}
